Skip to content

如何获取 iframe 的 document

https://javascript.info/cross-window-communication#iframe-wrong-document-pitfall

立即访问 contentDocument 与在 iframe 加载后访问 contentDocument 不同。

js
<iframe src="/" id="iframe"></iframe>

<script>
  let oldDoc = iframe.contentDocument;
  iframe.onload = function() {
    let newDoc = iframe.contentDocument;
    // 加载的document与初始的document不同!
    alert(oldDoc == newDoc); // false
  };
</script>

因此,可以在 iframe 加载后访问正确的 contentDocument

但是,如果需要尽快访问正确的 contentDocument,可以使用 setInterval 来检查 contentDocument 是否加载,在加载后尽快访问。

js
<iframe src="/" id="iframe"></iframe>

<script>
  let oldDoc = iframe.contentDocument;

  // every 100 ms check if the document is the new one
  let timer = setInterval(() => {
    let newDoc = iframe.contentDocument;
    if (newDoc == oldDoc) return;

    alert("New document is here!");

    clearInterval(timer); // 取消 setInterval,不再需要了
  }, 100);
</script>